<template>
  <div class="pdf-editor-container">
    <div id="webviewer" ref="webviewer" class="webviewer"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, onBeforeUnmount } from 'vue';
import WebViewer from '@pdftron/webviewer';

const props = defineProps({
  pdfUrl: {
    type: String,
    default: 'sample.pdf'
  },
  placedControls: {
    type: Array,
    default: () => []
  },
  selectedControl: {
    type: Object,
    default: null
  }
});

const emit = defineEmits([
  'control-dropped',
  'control-selected',
  'control-updated',
  'control-resized',
  'control-moved',
  'viewer-ready'
]);

const webviewer = ref(null);
let instance = null; // 存储 WebViewer 实例
let documentViewer = null;
let annotManager = null;

// 跟踪控件和注释的映射关系
const controlAnnotMap = new Map();

onMounted(async () => {
  // 初始化 WebViewer
  instance = await initWebViewer();
  
  // 阻止默认的缩放手势
  document.addEventListener('gesturestart', function(e) {
    e.preventDefault();
    return false;
  });
  
  document.addEventListener('gesturechange', function(e) {
    e.preventDefault();
    return false;
  });
  
  document.addEventListener('gestureend', function(e) {
    e.preventDefault();
    return false;
  });
  
  // 阻止键盘快捷键缩放
  document.addEventListener('keydown', function(e) {
    if ((e.ctrlKey || e.metaKey) && (e.key === '+' || e.key === '-' || e.key === '0')) {
      e.preventDefault();
      return false;
    }
  });
});

onBeforeUnmount(() => {
  // 清理 WebViewer 实例
  if (instance) {
    instance.dispose();
    instance = null;
  }
});

watch(
  () => props.pdfUrl,
  (newUrl) => {
    if (newUrl && instance) {
      loadDocument(newUrl);
    }
  }
);

watch(
  () => props.selectedControl,
  (newControl) => {
    if (newControl && annotManager) {
      // 找到对应的注释并选中
      const annotation = controlAnnotMap.get(newControl.id);
      if (annotation) {
        annotManager.selectAnnotation(annotation);
      }
    }
  }
);

// 当 placedControls 发生变化时，同步到 WebViewer
// 使用 ref 来追踪上次处理的控件数组，避免无限循环
let lastProcessedControls = [];
let isProcessing = false;

watch(
  () => props.placedControls,
  (newControls) => {
    // 避免在处理过程中再次触发
    if (isProcessing) {
      return;
    }
    
    // 检查是否真的有变化（比较控件ID和数量）
    const newControlIds = newControls.map(c => c.id).sort();
    const lastControlIds = lastProcessedControls.map(c => c.id).sort();
    
    // 只有在控件数量或ID发生变化时才触发同步
    if (JSON.stringify(newControlIds) === JSON.stringify(lastControlIds)) {
      return;
    }
    
    console.log('🔄 同步控件到PDF:', newControls.length, '个控件');
    
    // 记录当前处理的控件列表
    lastProcessedControls = JSON.parse(JSON.stringify(newControls));
    
    // 执行同步
    syncControlsToAnnotations();
  },
  { deep: false } // 改为 false，避免深度监听导致的无限循环
);

const initWebViewer = async () => {
  try {
    // 初始化 PDFTron WebViewer，使用更安全的配置
    return WebViewer(
      {
        path: '/lib',  // WebViewer 库文件路径
        initialDoc: props.pdfUrl,
        fullAPI: true,
        enableAnnotations: true,
        // 简化 UI 配置
        uiConfig: {
          showLeftPanel: false,
          showBottomToolbar: false,
          showTopToolbar: false
        }
      },
      webviewer.value
    ).then(instance => {
      try {
        const { documentViewer: docViewer, annotationManager, Annotations } = instance.Core;
        documentViewer = docViewer;
        annotManager = annotationManager;

        // 监听文档加载完成事件
        docViewer.addEventListener('documentLoaded', () => {
          try {
            // 延迟执行 UI 配置，确保 WebViewer 完全初始化
            setTimeout(() => {
              try {
                // 安全地禁用元素
                const elementsToDisable = [
                  'leftPanel',
                  'header',
                  'toolsHeader',
                  'thumbnailsPanel'
                ];
                
                elementsToDisable.forEach(element => {
                  try {
                    instance.UI.disableElement(element);
                  } catch (e) {
                    console.warn(`无法禁用元素 ${element}:`, e);
                  }
                });

                // 安全地关闭元素
                const elementsToClose = [
                  'leftPanel',
                  'thumbnailsPanel'
                ];
                
                elementsToClose.forEach(element => {
                  try {
                    instance.UI.closeElement(element);
                  } catch (e) {
                    console.warn(`无法关闭元素 ${element}:`, e);
                  }
                });

                // 设置缩放
                instance.UI.setZoomLevel(1.0);
                docViewer.setFitMode(instance.UI.FitMode.FitWidth);
                
              } catch (e) {
                console.warn('设置 UI 时出现警告:', e);
              }
            }, 200);
            
            // 获取页面信息
            const pageCount = docViewer.getPageCount();
            console.log(`PDF加载完成，共${pageCount}页`);
            
            // 记录PDF坐标系信息
            window.pdfInfo = {
              pageCount,
              pageInfo: {},
              documentId: props.pdfUrl,
              timestamp: new Date().toISOString()
            };
            
            for (let i = 1; i <= pageCount; i++) {
              try {
                const pageInfo = docViewer.getPageInfo(i);
                window.pdfInfo.pageInfo[i] = pageInfo;
              } catch (error) {
                console.warn(`无法获取页面${i}信息:`, error.message);
                // 使用备用方法获取页面信息
                try {
                  const page = docViewer.getDocument().getPageInfo(i);
                  window.pdfInfo.pageInfo[i] = page;
                } catch (fallbackError) {
                  // 设置默认值
                  window.pdfInfo.pageInfo[i] = { width: 612, height: 792 }; // 标准A4尺寸
                }
              }
            }
            
            // 同步现有控件
            setTimeout(() => {
              if (props.placedControls && props.placedControls.length > 0) {
                syncControlsToAnnotations();
              }
              emit('viewer-ready', instance);
            }, 300);
            
          } catch (error) {
            console.error('文档加载后处理出错:', error);
          }
        });

        // 在 WebViewer 完全初始化后设置其他功能
        setTimeout(() => {
          try {
            // 处理注释选择事件
            annotManager.addEventListener('annotationSelected', (annotations, action) => {
              if (annotations.length === 1) {
                const annotation = annotations[0];
                const controlId = annotation.CustomData?.controlId;
                if (controlId) {
                  // 找到对应的控件并选中
                  const control = props.placedControls.find(c => c.id === controlId);
                  if (control && (!props.selectedControl || props.selectedControl.id !== controlId)) {
                    emit('control-selected', controlId);
                  }
                }
              } else if (annotations.length === 0 && props.selectedControl) {
                // 取消选择
                emit('control-selected', null);
              }
            });

            // 处理注释修改事件
            annotManager.addEventListener('annotationChanged', (annotations, action) => {
              // 只处理移动和调整大小的操作
              if (action === 'modify') {
                annotations.forEach(annotation => {
                  const controlId = annotation.CustomData?.controlId;
                  if (controlId) {
                    const control = props.placedControls.find(c => c.id === controlId);
                    if (control) {
                      updateControlFromAnnotation(control, annotation);
                    }
                  }
                });
              }
            });

            // 设置拖放功能
            setupDragDrop(instance);
            
            // 进一步的 UI 清理
            setTimeout(() => {
              try {
                // 隐藏顶部工具栏
                const headerElement = document.querySelector('.Header');
                if (headerElement) {
                  headerElement.style.display = 'none';
                }
                
                // 隐藏左侧面板
                const leftPanelElement = document.querySelector('.left-panel, .LeftPanel');
                if (leftPanelElement) {
                  leftPanelElement.style.display = 'none';
                }
                
                // 隐藏缩放相关元素
                const zoomElements = document.querySelectorAll(
                  '[data-element="zoom"], [data-element="zoomSelector"], .zoom-wrapper, .ZoomOverlay'
                );
                zoomElements.forEach(element => {
                  if (element) {
                    element.style.display = 'none';
                    element.style.visibility = 'hidden';
                  }
                });
                
                // 设置缩放限制
                instance.UI.setMinZoomLevel(1.0);
                instance.UI.setMaxZoomLevel(1.0);
                
                // 禁用缩放相关的事件
                const viewerElement = docViewer.getScrollViewElement();
                if (viewerElement) {
                  viewerElement.style.touchAction = 'pan-x pan-y';
                  
                  // 覆盖默认的wheel事件处理
                  viewerElement.addEventListener('wheel', function(e) {
                    if (e.ctrlKey) {
                      e.preventDefault();
                      return false;
                    }
                  }, { passive: false });
                  
                  // 阻止触摸缩放
                  viewerElement.addEventListener('touchmove', function(e) {
                    if (e.touches.length > 1) {
                      e.preventDefault();
                      return false;
                    }
                  }, { passive: false });
                }
                
              } catch (e) {
                console.warn('UI 清理时出现警告:', e);
              }
            }, 500);
            
          } catch (error) {
            console.warn('设置事件监听器时出现警告:', error);
          }
        }, 100);
        
      } catch (error) {
        console.error('WebViewer 初始化出错:', error);
        throw error;
      }
    }).catch(error => {
      console.error('WebViewer 创建失败:', error);
      throw error;
    });
  } catch (error) {
    console.error('initWebViewer 出错:', error);
    throw error;
  }
};

const loadDocument = (url) => {
  if (instance) {
    instance.UI.loadDocument(url);
  }
};

// 计算PDF中的绝对坐标位置（从第一页的左上角开始计算）
const calculateAbsolutePosition = (pageNumber, x, y) => {
  if (!documentViewer) return { x, y };
  
  // 如果是第一页，直接返回原坐标
  if (pageNumber === 1) return { x, y };
  
  // 获取前面所有页面的高度总和
  let totalHeight = 0;
  for (let i = 1; i < pageNumber; i++) {
    try {
      let pageInfo;
      if (typeof documentViewer.getPageInfo === 'function') {
        pageInfo = documentViewer.getPageInfo(i);
      } else if (documentViewer.getDocument && typeof documentViewer.getDocument().getPageInfo === 'function') {
        pageInfo = documentViewer.getDocument().getPageInfo(i);
      } else {
        pageInfo = { width: 612, height: 792 };
      }
      totalHeight += pageInfo.height;
      // 可以考虑添加页间距
      totalHeight += 20; // 页间距，可以根据实际情况调整
    } catch (error) {
      console.error(`获取页面 ${i} 信息失败:`, error);
      totalHeight += 792; // 使用默认高度
      totalHeight += 20;
    }
  }
  
  // 返回绝对坐标
  return {
    x: x,
    y: y + totalHeight
  };
};

// 将控件同步为注释
const syncControlsToAnnotations = () => {
  // 设置处理状态，避免无限循环
  isProcessing = true;
  
  if (!annotManager || !documentViewer) {
    console.warn('❌ annotManager 或 documentViewer 未初始化');
    isProcessing = false;
    return;
  }

  if (!instance || !instance.Core) {
    console.warn('❌ instance 或 instance.Core 未初始化，延迟执行...');
    // 延迟执行，等待初始化完成
    setTimeout(() => {
      isProcessing = false; // 重置状态
      syncControlsToAnnotations();
    }, 200);
    return;
  }

  try {
    // 获取现有的所有注释
    const allAnnots = annotManager.getAnnotationsList();
    
    // 删除所有控件相关的注释
    const controlAnnots = allAnnots.filter(annot => annot.CustomData?.controlId);
    if (controlAnnots.length > 0) {
      annotManager.deleteAnnotations(controlAnnots);
    }
    
    // 清空映射关系
    controlAnnotMap.clear();
    
    // 为每个控件创建对应的注释
    props.placedControls.forEach((control) => {
      createAnnotationFromControl(control);
    });
    
    console.log('✅ 控件同步完成!', props.placedControls.length, '个控件');
  } catch (error) {
    console.error('❌ 同步控件时发生错误:', error);
  } finally {
    // 重置处理状态
    isProcessing = false;
  }
};

// 获取控件在PDF中的精确位置
const getControlAbsolutePosition = (control) => {
  // 如果控件有自己的坐标比例，使用它
  if (control.coordinateRatio) {
    let pageInfo;
    try {
      if (typeof documentViewer.getPageInfo === 'function') {
        pageInfo = documentViewer.getPageInfo(control.page);
      } else if (documentViewer.getDocument && typeof documentViewer.getDocument().getPageInfo === 'function') {
        pageInfo = documentViewer.getDocument().getPageInfo(control.page);
      } else {
        pageInfo = { width: 612, height: 792 };
      }
    } catch (error) {
      console.error('获取页面信息失败:', error);
      pageInfo = { width: 612, height: 792 };
    }
    
    return {
      x: pageInfo.width * control.coordinateRatio.x,
      y: pageInfo.height * control.coordinateRatio.y,
      width: pageInfo.width * control.coordinateRatio.width,
      height: pageInfo.height * control.coordinateRatio.height
    };
  }

  // 否则直接返回原始坐标
  return {
    x: control.x,
    y: control.y,
    width: control.width,
    height: control.height
  };
};

// 计算控件相对于PDF页面的坐标比例
const calculateControlCoordinateRatio = (control, pageInfo) => {
  if (!pageInfo) {
    try {
      if (typeof documentViewer.getPageInfo === 'function') {
        pageInfo = documentViewer.getPageInfo(control.page);
      } else if (documentViewer.getDocument && typeof documentViewer.getDocument().getPageInfo === 'function') {
        pageInfo = documentViewer.getDocument().getPageInfo(control.page);
      } else {
        pageInfo = { width: 612, height: 792 };
      }
    } catch (error) {
      console.error('获取页面信息失败:', error);
      pageInfo = { width: 612, height: 792 };
    }
  }
  
  // 计算比例
  return {
    x: control.x / pageInfo.width,
    y: control.y / pageInfo.height,
    width: control.width / pageInfo.width,
    height: control.height / pageInfo.height
  };
};

// 根据控件创建注释
const createAnnotationFromControl = (originalControl) => {
  // 创建控件的副本，避免修改原始 props
  const control = { ...originalControl };
  
  try {
    if (!annotManager || !documentViewer || !instance || !instance.Core) {
      console.error('❌ WebViewer 组件未完全初始化');
      return;
    }
    
    const { Annotations } = instance.Core;
    
    if (!Annotations) {
      console.error('❌ Annotations 类未找到');
      return;
    }
    
    let annotation;

  // 根据控件类型创建不同类型的注释
  switch (control.type) {
    case 'text-input':
      annotation = new Annotations.FreeTextAnnotation();
      annotation.setContents(control.properties?.placeholder || '请输入文本');
      // 设置 FreeText 注释的样式
      annotation.setColor(new Annotations.Color(0, 0, 0, 1)); // 黑色文字
      annotation.setFillColor(new Annotations.Color(255, 255, 255, 0.8)); // 白色背景
      annotation.setStrokeColor(new Annotations.Color(128, 128, 128, 1)); // 灰色边框
      annotation.setStrokeThickness(1);
      annotation.setFontSize(12);
      break;
    case 'textarea':
      annotation = new Annotations.FreeTextAnnotation();
      annotation.setContents(control.properties?.placeholder || '请输入多行文本');
      // 设置 FreeText 注释的样式
      annotation.setColor(new Annotations.Color(0, 0, 0, 1)); // 黑色文字
      annotation.setFillColor(new Annotations.Color(255, 255, 255, 0.8)); // 白色背景
      annotation.setStrokeColor(new Annotations.Color(128, 128, 128, 1)); // 灰色边框
      annotation.setStrokeThickness(1);
      annotation.setFontSize(12);
      break;
    case 'select':
      annotation = new Annotations.FreeTextAnnotation();
      annotation.setContents(control.properties?.placeholder || '请选择');
      // 设置 FreeText 注释的样式
      annotation.setColor(new Annotations.Color(0, 0, 0, 1)); // 黑色文字
      annotation.setFillColor(new Annotations.Color(240, 240, 240, 0.8)); // 浅灰色背景
      annotation.setStrokeColor(new Annotations.Color(128, 128, 128, 1)); // 灰色边框
      annotation.setStrokeThickness(1);
      annotation.setFontSize(12);
      break;
    case 'radio':
      annotation = new Annotations.RectangleAnnotation();
      annotation.setColor(new Annotations.Color(200, 150, 150, 0.5));
      break;
    case 'checkbox':
      annotation = new Annotations.RectangleAnnotation();
      annotation.setColor(new Annotations.Color(128, 128, 128, 0.5));
      break;
    case 'checkbox-group':
      annotation = new Annotations.RectangleAnnotation();
      annotation.setColor(new Annotations.Color(150, 200, 150, 0.5));
      break;
    case 'signature':
      annotation = new Annotations.RectangleAnnotation();
      annotation.setColor(new Annotations.Color(0, 128, 255, 0.5));
      break;
    default:
      annotation = new Annotations.RectangleAnnotation();
      annotation.setColor(new Annotations.Color(200, 200, 200, 0.5));
  }

  if (!annotation) {
    console.error('❌ 注释创建失败');
    return;
  }

  // 设置注释的基本属性
  const pageNumber = control.page || 1;
  let pageInfo;
  
  try {
    if (typeof documentViewer.getPageInfo === 'function') {
      pageInfo = documentViewer.getPageInfo(pageNumber);
    } else if (documentViewer.getDocument && typeof documentViewer.getDocument().getPageInfo === 'function') {
      pageInfo = documentViewer.getDocument().getPageInfo(pageNumber);
    } else {
      pageInfo = { width: 612, height: 792 };
    }
  } catch (error) {
    console.error('获取页面信息失败:', error);
    pageInfo = { width: 612, height: 792 };
  }
  
  // 如果控件有坐标比例信息，使用比例计算实际位置
  let x, y, width, height;
  
  if (control.coordinateRatio) {
    // 使用坐标比例计算实际位置
    x = pageInfo.width * control.coordinateRatio.x;
    y = pageInfo.height * control.coordinateRatio.y;
    width = pageInfo.width * control.coordinateRatio.width;
    height = pageInfo.height * control.coordinateRatio.height;
  } else {
    // 使用绝对像素位置
    x = control.x; 
    y = control.y;
    width = control.width;
    height = control.height;
  }

  // 设置注释位置和大小
  annotation.setRect(new instance.Core.Math.Rect(x, y, x + width, y + height));
  annotation.setPageNumber(pageNumber);
  
  // 设置自定义数据，关联控件ID
  const coordinateRatio = control.coordinateRatio || calculateControlCoordinateRatio(control, pageInfo);
  annotation.CustomData = {
    controlId: control.id,
    controlType: control.type,
    coordinateRatio: coordinateRatio // 保存坐标比例信息
  };
  
  // 添加注释到文档
  annotManager.addAnnotation(annotation);
  
  // 重绘以显示注释
  annotManager.redrawAnnotation(annotation);
  
  // 存储映射关系
  controlAnnotMap.set(control.id, annotation);
  
  console.log(`✅ 控件注释创建成功: ${control.type}(${control.id})`);
  
  } catch (error) {
    console.error('❌ 创建注释时发生错误:', error);
  }
};

// 从注释更新控件的位置和大小
const updateControlFromAnnotation = (control, annotation) => {
  const rect = annotation.getRect();
  
  // 从注释矩形获取坐标和尺寸
  const x = rect.x1;
  const y = rect.y1;
  const width = rect.getWidth();
  const height = rect.getHeight();
  
  // 获取页面信息，用于更新控件在固定坐标系中的位置
  const pageNumber = annotation.getPageNumber();
  let pageInfo;
  
  try {
    if (typeof documentViewer.getPageInfo === 'function') {
      pageInfo = documentViewer.getPageInfo(pageNumber);
    } else if (documentViewer.getDocument && typeof documentViewer.getDocument().getPageInfo === 'function') {
      pageInfo = documentViewer.getDocument().getPageInfo(pageNumber);
    } else {
      pageInfo = { width: 612, height: 792 };
    }
  } catch (error) {
    console.error('获取页面信息失败:', error);
    pageInfo = { width: 612, height: 792 };
  }
  
  // 计算新的坐标比例，确保在不同分辨率下保持位置
  const newCoordinateRatio = {
    x: x / pageInfo.width,
    y: y / pageInfo.height,
    width: width / pageInfo.width,
    height: height / pageInfo.height
  };
  
  // 更新控件的坐标比例
  control.coordinateRatio = newCoordinateRatio;
  
  console.log(`控件位置更新: ${control.id} 在页面${pageNumber} (${x.toFixed(0)}, ${y.toFixed(0)})`);
  
  // 更新控件位置和尺寸
  emit('control-moved', control.id, x, y, pageNumber);
  emit('control-resized', control.id, width, height);
};

// 设置拖放处理
const setupDragDrop = (instance) => {
  try {
    const { documentViewer } = instance.Core;
    
    // 获取多个可能的DOM元素
    let viewerElement, scrollElement, containerElement;
    
    // 尝试多种方法获取 viewerElement
    try {
      viewerElement = instance.UI.docViewer.getViewerElement();
    } catch (error) {
      try {
        viewerElement = documentViewer.getViewerElement();
      } catch (error2) {
        try {
          viewerElement = document.querySelector('#webviewer .DocumentContainer') || 
                          document.querySelector('#webviewer .Core__container') ||
                          document.querySelector('#webviewer .Core') ||
                          document.querySelector('#webviewer iframe') ||
                          document.querySelector('#webviewer');
        } catch (error3) {
          console.warn('无法获取 viewerElement');
        }
      }
    }
    
    try {
      scrollElement = documentViewer.getScrollViewElement();
    } catch (error) {
      try {
        scrollElement = document.querySelector('#webviewer .scrollContainer') || 
                       document.querySelector('#webviewer .DocumentContainer') ||
                       viewerElement;
      } catch (error2) {
        console.warn('无法获取 scrollElement');
      }
    }
    
    try {
      containerElement = document.getElementById('webviewer');
    } catch (error) {
      console.warn('无法获取 containerElement');
    }
  
  // 处理控件放置的函数
  const handleControlDrop = (e, targetElement) => {
    console.log('🎯 控件拖拽事件触发');
    
    try {
      e.preventDefault();
      e.stopPropagation(); // 阻止事件冒泡，避免重复处理
      
      // 检查是否已经在处理中，避免重复处理
      if (window.isProcessingDrop) {
        return;
      }
      
      window.isProcessingDrop = true;
      
      // 获取拖拽的控件类型
      const controlType = window.draggingControlType;
      
      if (!controlType) {
        console.warn('❌ 未找到控件类型');
        window.isProcessingDrop = false;
        return;
      }
      
      // 获取当前页面信息
      const currentPage = documentViewer.getCurrentPage();
      
      let pageInfo;
      
      try {
        // 尝试多种方法获取页面信息
        if (typeof documentViewer.getPageInfo === 'function') {
          pageInfo = documentViewer.getPageInfo(currentPage);
        } else if (documentViewer.getDocument && typeof documentViewer.getDocument().getPageInfo === 'function') {
          pageInfo = documentViewer.getDocument().getPageInfo(currentPage);
        } else {
          // 使用默认页面尺寸
          pageInfo = { width: 612, height: 792 };
        }
        
      } catch (error) {
        console.error('❌ 获取页面信息失败:', error);
        pageInfo = { width: 612, height: 792 };
      }
      
      // 确保有有效的 viewerElement
      if (!viewerElement) {
        viewerElement = document.querySelector('#webviewer .DocumentContainer') || 
                        document.querySelector('#webviewer .Core__container') ||
                        document.querySelector('#webviewer .Core') ||
                        document.querySelector('#webviewer') ||
                        containerElement;
      }
      
      if (!viewerElement) {
        console.error('❌ 无法获取 viewerElement，跳过坐标计算');
        return;
      }
      
      // 获取点击位置相对于 viewer 的坐标
      const viewerRect = viewerElement.getBoundingClientRect();
      const clientX = e.clientX - viewerRect.left;
      const clientY = e.clientY - viewerRect.top;

      // 简化坐标转换 - 直接使用基本计算
      let zoom, scrollElement, scrollLeft, scrollTop;
      
      try {
        // 尝试多种方法获取缩放比例
        if (typeof documentViewer.getZoom === 'function') {
          zoom = documentViewer.getZoom();
        } else if (typeof documentViewer.getZoomLevel === 'function') {
          zoom = documentViewer.getZoomLevel();
        } else if (instance && instance.UI && typeof instance.UI.getZoomLevel === 'function') {
          zoom = instance.UI.getZoomLevel();
        } else {
          zoom = 1.0; // 默认缩放比例
        }
      } catch (error) {
        zoom = 1.0; // 默认缩放比例
      }
      
      try {
        scrollElement = documentViewer.getScrollViewElement();
        scrollLeft = scrollElement ? scrollElement.scrollLeft : 0;
        scrollTop = scrollElement ? scrollElement.scrollTop : 0;
      } catch (error) {
        scrollLeft = 0;
        scrollTop = 0;
      }
      
      // 计算PDF坐标
      const pdfX = (clientX + scrollLeft) / zoom;
      const pdfY = (clientY + scrollTop) / zoom;
      
      // 根据控件类型设置默认尺寸
      let defaultWidth = 150;
      let defaultHeight = 30;
      let controlTypeName = '';
      
      switch (controlType) {
        case 'text-input':
          controlTypeName = '单行文本输入框';
          defaultWidth = 150;
          defaultHeight = 30;
          break;
        case 'textarea':
          controlTypeName = '多行文本输入框';
          defaultWidth = 200;
          defaultHeight = 80;
          break;
        case 'checkbox':
          controlTypeName = '复选框';
          defaultWidth = 20;
          defaultHeight = 20;
          break;
        case 'radio':
          controlTypeName = '单选按钮组';
          defaultWidth = 150;
          defaultHeight = 80;
          break;
        case 'signature':
          controlTypeName = '签名区域';
          defaultWidth = 200;
          defaultHeight = 100;
          break;
        default:
          controlTypeName = '未知控件';
          defaultWidth = 100;
          defaultHeight = 30;
      }
      
      // 计算坐标比例
      const coordinateRatio = {
        x: pdfX / pageInfo.width,
        y: pdfY / pageInfo.height,
        width: defaultWidth / pageInfo.width,
        height: defaultHeight / pageInfo.height
      };
      
      // 生成控件ID
      const controlId = `control_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
      
      console.log(`✅ ${controlTypeName} 已放置在第${currentPage}页 (${pdfX.toFixed(0)}, ${pdfY.toFixed(0)})`);
      
      // 触发控件放置事件
      emit('control-dropped', {
        id: controlId,
        type: controlType,
        typeName: controlTypeName,
        x: pdfX,
        y: pdfY,
        width: defaultWidth,
        height: defaultHeight,
        page: currentPage,
        coordinateRatio: coordinateRatio,
        properties: {
          placeholder: `请输入${controlTypeName}`,
          required: false
        }
      });
      
      // 清除拖拽状态
      window.draggingControlType = null;
      window.isProcessingDrop = false;
      
    } catch (error) {
      console.error('❌ 控件拖拽处理出错:', error);
      window.isProcessingDrop = false; // 确保错误时也清除状态
    }
  };
  
  // 为多个元素添加事件监听
  const targets = [viewerElement, scrollElement, containerElement].filter(Boolean);
  
  targets.forEach((element, index) => {
    // 添加 dragenter 事件
    element.addEventListener('dragenter', (e) => {
      e.preventDefault();
      e.stopPropagation();
    });
    
    element.addEventListener('dragover', (e) => {
      e.preventDefault();
      e.stopPropagation();
      e.dataTransfer.dropEffect = 'move';
    });
    
    element.addEventListener('drop', (e) => {
      handleControlDrop(e, element);
    });
    
    // 备用方案：使用 mouseup 事件
    element.addEventListener('mouseup', (e) => {
      if (window.draggingControlType) {
        handleControlDrop(e, element);
      }
    });
    
    // 额外的备用事件监听
    element.addEventListener('dragend', (e) => {
      if (window.draggingControlType) {
        handleControlDrop(e, element);
      }
    });
  });
  
  } catch (error) {
    console.error('❌ setupDragDrop 出错:', error);
  }
};
</script>

<style scoped>
.pdf-editor-container {
  height: 100%;
  width: 100%;
  position: relative;
  display: flex;
  justify-content: center; /* 水平居中 */
  overflow: auto;
  background-color: #f0f2f5;
}

.webviewer {
  height: 100%;
  width: 100%;
  max-width: 630px; /* 设置固定宽度 */
  margin: 0 auto; /* 自动边距使内容居中 */
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
}

:global(.Header) {
  display: none !important;
}

:global(.ToolbarHeader) {
  display: none !important;
}

:global(.left-panel) {
  display: none !important;
}

:global(.LeftPanel) {
  display: none !important;
}

:global(.document-viewer) {
  touch-action: pan-x pan-y; 
}

:global(.DocumentContainer) {
  touch-action: pan-x pan-y; 
  transform: scale(1.0) !important; 
  transform-origin: center !important;
}

/* 隐藏所有与缩放相关的UI元素 */
:global(.ZoomOverlay),
:global(.ZoomContainer), 
:global(.ZoomPercentage), 
:global(.ZoomIn), 
:global(.ZoomOut) {
  display: none !important;
}

/* 隐藏顶部的缩放按钮和百分比显示 */
:global([data-element="zoom"]),
:global([data-element="zoomSelector"]),
:global([data-element="zoomIn"]),
:global([data-element="zoomOut"]),
:global(.zoom-wrapper),
:global(.ZoomOverlay),
:global(.zoom-overlay),
:global(.zoom-container),
:global(.zoom-button),
:global(.zoom-select-container),
:global(.dropdown-item[data-element*="zoom"]) {
  display: none !important;
  visibility: hidden !important;
  opacity: 0 !important;
  pointer-events: none !important;
}

/* 完全禁用可能的缩放交互 */
:global(.page-container) {
  transform: none !important; /* 确保没有任何缩放变换 */
  transition: none !important; /* 禁用所有过渡效果，防止缩放动画 */
}

/* 禁止缩放按钮在顶部的显示 */
:global(.ModularHeader [data-element*="zoom"]),
:global(.Header [data-element*="zoom"]),
:global(.header [data-element*="zoom"]),
:global([data-element="viewControlsButton"]) {
  display: none !important;
}

/* 强制PDF页面固定大小 */
:global(.page),
:global(.page-wrapper) {
  transform: scale(1.0) !important;
  transform-origin: center !important;
  transition: none !important;
}

/* 完全禁用WebViewer内部的缩放变换 */
:global(.pageContainer),
:global(.document-container),
:global([data-testid="page-container"]) {
  transform: none !important;
  zoom: 1 !important;
}

/* 隐藏任何可能的缩放UI */
:global(.zoom-level),
:global(.fit-mode-button),
:global(.zoom-percentage) {
  display: none !important;
}
</style>